package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.excetion.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishService;
import com.itheima.reggie.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ICategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private IDishService dishService;
    @Autowired
    private ISetmealService setmealService;

    /**
     * 根据id删除  删除前需要进行判断
     * @param id
     */
    @Override
    public void remove(Long id) {
        //1、检查当前分类下是否有对应的菜品
        // SELECT COUNT(*) FROM `dish` WHERE category_id = 1397844263642378242
        // 结果大于0 ，则不能删除  代码结束 --> 自定义一个业务异常，然后抛出  throw new BusinessException("该分类下有菜品，不能删除");
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,id);
        int count = dishService.count(qw);
        if (count>0){
            throw new BusinessException("该分类下有菜品，不能删除");
        }
        //2、检查当前分类下是否有对应的套餐
        // SELECT COUNT(*) FROM `setmeal` WHERE category_id= 1397844263642378242
        //结果大于0 ，则不能删除  代码结束 --> 自定义一个业务异常，然后抛出 throw new BusinessException("该分类下有套餐，不能删除");
        LambdaQueryWrapper<Setmeal> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(Setmeal::getCategoryId,id);
        int count1 = setmealService.count(qw1);
        if (count1>0){
            throw  new BusinessException("该分类下有套餐，不能删除");
        }
        //3、可以删除,则调用mapper直接删除 categoryMapper.deleteById(id);
        super.removeById(id);

    }
}
